use crate::models::notifications::{self, CreateParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/notifications", post(create))
        .route("/notifications/:id", get(get_by_id))
        .route("/notifications/:id/delete", post(delete))
        .route(
            "/notifications/by-notifiable/:notifiable_type/:notifiable_id",
            get(get_by_notifiable),
        )
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let notification = notifications::Model::create(&state.db, &params).await?;
    format::json(notification)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let notification = notifications::Model::find_by_id(&state.db, &id).await?;
    format::json(notification)
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let notification = notifications::Model::find_by_id(&state.db, &id).await?;
    notification.delete(&state.db).await?;
    format::json(())
}

async fn get_by_notifiable(
    State(state): State<AppContext>,
    axum::extract::Path((notifiable_type, notifiable_id)): axum::extract::Path<(String, String)>,
) -> Result<Response> {
    let notifications =
        notifications::Model::find_by_notifiable(&state.db, &notifiable_type, &notifiable_id)
            .await?;
    format::json(notifications)
}
